package org.xiangfei.manager.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BaseJdbcTemplateDao<T> {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    protected Page<T> queryBySqlPage(String sql, Object[] params, Pageable pageable, Class<T> clazz) {

        StringBuffer totalSql = new StringBuffer(" select count(*) from ( ");
        totalSql.append(sql);
        totalSql.append(" ) totalTable ");

        StringBuffer pageSql = new StringBuffer(sql + " limit " + pageable.getOffset() + "," + pageable.getPageSize());

        System.out.println(pageSql);

        Integer totalElements = jdbcTemplate.queryForObject(totalSql.toString(), params, Integer.class);

        List<T> content = jdbcTemplate.query(pageSql.toString(), new BeanPropertyRowMapper<T>(clazz), params);
        Page<T> page = new PageImpl<T>(content, pageable, totalElements);
        return page;
    }

    protected List<T> queryListBySql(String sql, Object[] params, Class<T> clazz) {
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<T>(clazz), params);
    }

    protected int update(String sql, Object[] params) {
        return jdbcTemplate.update(sql, params);
    }
}
